package com.xue.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import com.xue.dao.UserRepository;

/**
 * 
 * @author 北京八维博大科技 薛建新
 * @date 2022年4月28日 下午2:43:12
 * @Copyright 北京八维博大科技
 */
@EnableWebSecurity
public class SecurityConfig {
	@Bean
	SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
		// @formatter:off
		return http
		          //设置了<iframe>标签的“同源策略”，解决了上面出现的问题
				  //https://blog.csdn.net/weixin_43981241/article/details/108240756
		          .headers().frameOptions().sameOrigin()
		          .and()
		          //使得h2 console页面不去做csrf检查
		          .csrf()
		          .ignoringAntMatchers("/h2-console/**")
		          .and()
		          .authorizeRequests()
		          //使得访问h2 console时，不需要先登录系统
		          .antMatchers("/h2-console/**").permitAll()
		          .and()
		          .authorizeRequests(authorizeRequests -> authorizeRequests.anyRequest().anonymous())
		          .formLogin()
		          .and()
		          .build();
		// @formatter:on

	}

	@Bean
	UserDetailsService userDetailsService(UserRepository userRepo) {
		return username -> userRepo.findByUsername(username);
	}

//// 内容用户，只用于测试 
//	@Bean
//	public UserDetailsService userDetailsService(PasswordEncoder encoder) {
//		// @formatter:off
//		UserDetails u1 = User.withUsername("a1")
//				.password(encoder.encode("123"))
//				.roles("ADMIN")//没有必要写成"ROLE_ADMIN"
//				.build();
//		UserDetails u2 = User.withUsername("u1")
//				.password(encoder.encode("123"))
//				.roles("USER")//没有必要写成"ROLE_ADMIN"
//				.build();
//		// @formatter:on
//
//		return new InMemoryUserDetailsManager(u1, u2);
//	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

}
